<template>
  <div>
    <el-form ref="form" label-width="80px" :model="spuList">
      <!-- SPU名称 -->
      <el-form-item label="SPU名称">
        <el-input placeholder="SPU名称" v-model="spuList.spuName"></el-input>
      </el-form-item>
      <!--品牌  -->
      <el-form-item label="品牌">
        <el-select placeholder="请选择品牌" v-model="spuList.tmId">
          <el-option
            :label="tm.tmName"
            :value="tm.id"
            v-for="tm in tradeMark"
            :key="tm.id"
          ></el-option>
        </el-select>
      </el-form-item>
      <!--SPU描述  -->
      <el-form-item label="SPU描述">
        <el-input
          type="textarea"
          placeholder="SPU描述"
          rows="4"
          v-model="spuList.description"
        ></el-input>
      </el-form-item>
      <!-- SPU图片 -->
      <el-form-item label="SPU图片">
        <el-upload
          action="/dev-api/admin/product/fileUpload"
          list-type="picture-card"
          :file-list="spuImageList"
          :on-preview="handlePictureCardPreview"
          :on-remove="handleRemove"
          :on-success="uploadSuccess"
        >
          <i class="el-icon-plus"></i>
        </el-upload>
        <el-dialog :visible.sync="dialogVisible">
          <img width="100%" :src="dialogImageUrl" alt="" />
        </el-dialog>
      </el-form-item>
      <!-- 销售属性 -->
      <el-form-item label="销售属性">
        <el-select
          :placeholder="`还有${unSelectSaleAttr.length}个未选择`"
          v-model="attrIdAndValue"
        >
          <el-option
            :label="unSelect.name"
            :value="`${unSelect.id}:${unSelect.name}`"
            v-for="unSelect in unSelectSaleAttr"
            :key="unSelect.id"
          ></el-option>
        </el-select>
        <el-button
          type="primary"
          icon="el-icon-plus"
          :disabled="!attrIdAndValue"
          @click="addSaleValue"
          >添加销售属性</el-button
        >
        <!-- 销售属性值列表 -->
        <el-table style="width: 100%" border :data="spuList.spuSaleAttrList">
          <el-table-column
            type="index"
            align="center"
            label="序号"
            width="80px"
          >
          </el-table-column>
          <el-table-column prop="saleAttrName" label="属性名" width="100px">
          </el-table-column>
          <el-table-column prop="prop" label="属性值名称列表" width="width">
            <template slot-scope="{ row }">
              <!--  @close="handleClose(tag)"-->
              <el-tag
                :key="tag.id"
                v-for="(tag, index) in row.spuSaleAttrValueList"
                closable
                :disable-transitions="false"
                @close="handleClose(row, index)"
              >
                {{ tag.saleAttrValueName }}
              </el-tag>
              <!--           @keyup.enter.native="handleInputConfirm"
                @blur="handleInputConfirm" -->
              <el-input
                class="input-new-tag"
                v-if="row.inputVisible"
                v-model="row.inputValue"
                ref="saveTagInput"
                size="small"
                @blur="handleInputConfirm(row)"
              >
              </el-input>
              <el-button
                v-else
                class="button-new-tag"
                size="small"
                @click="showInput(row)"
                >添加</el-button
              >
            </template>
          </el-table-column>
          <el-table-column prop="prop" label="操作" width="width">
            <template slot-scope="{ row, $index }">
              <el-button
                type="danger"
                icon="el-icon-delete"
                size="mini"
                @click="deleteSale(row, $index)"
              ></el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-form-item>
      <!-- 保存与取消按钮 -->
      <el-form-item>
        <el-button type="primary" @click="addOrUpdate">保存</el-button>
        <el-button @click="clearData">取消</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
export default {
  name: "SpuForm",
  data() {
    return {
      dialogImageUrl: "",
      dialogVisible: false,
      spuList: {
        category3Id: "",
        tmId: "",
        description: "",
        spuName: "",
        spuImageList: [
          /*          {
            id: 0,
            imgName: "string",
            imgUrl: "string",
            spuId: 0,
          }, */
        ],
        spuSaleAttrList: [
          /*           {
            baseSaleAttrId: 0,
            id: 0,
            saleAttrName: "string",
            spuId: 0,
            spuSaleAttrValueList: [
              {
                baseSaleAttrId: 0,
                id: 0,
                isChecked: "string",
                saleAttrName: "string",
                saleAttrValueName: "string",
                spuId: 0,
              },
            ],
          }, */
        ],
      },
      tradeMark: [],
      spuImageList: [],
      spuSaleAttrList: [],
      attrIdAndValue: "",
    };
  },
  methods: {
    handleRemove(file, fileList) {
      this.spuImageList = fileList;
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    //向服务器发请求获取数据
    async initSpuData(spu) {
      //获取spu信息
      let spuResult = await this.$API.spu.reqSpuList(spu.id);
      if (spuResult.code === 200) {
        this.spuList = spuResult.data;
      }
      //获取品牌信息列表
      let tradeMarkResult = await this.$API.spu.reqTradeMarkList();
      if (tradeMarkResult.code === 200) {
        this.tradeMark = tradeMarkResult.data;
      }
      //获取spu图片
      let spuImageResult = await this.$API.spu.reqSpuImageList(spu.id);
      if (spuImageResult.code === 200) {
        let arrList = spuImageResult.data;
        arrList.forEach((item) => {
          item.name = item.imgName;
          item.url = item.imgUrl;
        });
        this.spuImageList = arrList;
      }
      //获取销售属性
      let saleAttrListResult = await this.$API.spu.reqBaseSaleAttrList();
      if (saleAttrListResult.code === 200) {
        this.spuSaleAttrList = saleAttrListResult.data;
      }
    },
    //图片上传成功执行回调
    uploadSuccess(response, file, fileList) {
      this.spuImageList = fileList;
    },
    //点击添加销售属性按钮
    addSaleValue() {
      const [baseSaleAttrId, saleAttrName] = this.attrIdAndValue.split(":");
      let newSaleValue = {
        baseSaleAttrId,
        saleAttrName,
        spuSaleAttrValueList: [],
      };
      this.spuList.spuSaleAttrList.push(newSaleValue);
      this.attrIdAndValue = "";
    },
    //点击 属性值名称列表 添加按钮 显示输入框
    showInput(row) {
      this.$set(row, "inputVisible", true);
      this.$set(row, "inputValue", "");
    },
    //点击 属性值名称列表 input 显示span 失去焦点
    handleInputConfirm(row) {
      if (row.inputValue.trim() == "") {
        row.inputVisible = false;
        this.$message.error("输入值不能为空！");
      } else {
        let result = row.spuSaleAttrValueList.every((item) => {
          return item.saleAttrValueName != row.inputValue;
        });
        if (result) {
          const { baseSaleAttrId, inputValue } = row;
          let newSpuSale = { baseSaleAttrId, saleAttrValueName: inputValue };
          row.spuSaleAttrValueList.push(newSpuSale);
          row.inputVisible = false;
          this.$message({ type: "success", message: "添加成功" });
        } else {
          this.$message.error("添加值重复，请重新输入");
        }
      }
    },
    //点击 销售属性table操作 删除按钮
    deleteSale(row, $index) {
      this.spuList.spuSaleAttrList.splice($index, 1);
      this.$message({
        type: "success",
        message: `当前"${row.saleAttrName}"删除成功`,
      });
    },
    //点击 属性值名称列表 小叉叉 删除对应
    handleClose(row, index) {
      let result = row.spuSaleAttrValueList.splice(index, 1);
      const [obj] = result;
      this.$message({
        type: "success",
        message: `"${obj.saleAttrValueName}"删除成功`,
      });
    },
    //保存按钮
    async addOrUpdate() {
      //整理参数 将图片收集到spuList中
      this.spuList.spuImageList = this.spuImageList.map((item) => {
        return {
          imgName: item.name,
          imgUrl: item.response ? item.response.data : item.url,
        };
      });
      if (this.spuList.spuName == "" || this.spuList.description == "") {
        this.$message.error(`保存失败！"SPU管理"与"SPU描述"必须填写`);
      } else {
        //发请求保存或修改数据
        let result = await this.$API.spu.reqAddOrUpdateList(this.spuList);
        if (result.code === 200) {
          this.$message({
            type: "success",
            message: this.spuList.id ? "修改成功" : "保存成功",
          });
          this.$emit("changeScene", this.spuList.id ? "修改" : "保存");
          //清除数据  以免影响添加spu操作
          Object.assign(this._data, this.$options.data());
        }
      }
    },
    //点击取消按钮 清除数据
    clearData() {
      this.$emit("changeScene", "");
      //清除数据  以免影响添加spu操作
      Object.assign(this._data, this.$options.data());
    },
    //在父组件中点击添加SPU按钮触发此回调
    async getBrandAndSale(category3Id) {
      //由于点击添加spu按钮没有收集到category3Id,添加修改按钮服务器返回的有
      this.spuList.category3Id = category3Id;
      //获取品牌信息列表
      let tradeMarkResult = await this.$API.spu.reqTradeMarkList();
      if (tradeMarkResult.code === 200) {
        this.tradeMark = tradeMarkResult.data;
      }
      //获取销售属性
      let saleAttrListResult = await this.$API.spu.reqBaseSaleAttrList();
      if (saleAttrListResult.code === 200) {
        this.spuSaleAttrList = saleAttrListResult.data;
      }
    },
  },
  computed: {
    unSelectSaleAttr() {
      return this.spuSaleAttrList.filter((item) => {
        return this.spuList.spuSaleAttrList.every((item1) => {
          return item.name != item1.saleAttrName;
        });
      });
    },
  },
};
</script>

<style>
.el-tag + .el-tag {
  margin-left: 10px;
}
.button-new-tag {
  margin-left: 10px;
  height: 32px;
  line-height: 30px;
  padding-top: 0;
  padding-bottom: 0;
}
.input-new-tag {
  width: 90px;
  margin-left: 10px;
  vertical-align: bottom;
}
</style>